package com.joyance.springmvc.util;

import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

public class DateTool extends Directive {

    @Override
    public String getName() {
        return "dateTool";
    }


    @Override
    public int getType() {
        return LINE;
    }


    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException,
            MethodInvocationException {
        Node node0 = node.jjtGetChild(0);
        Object obj0 = node0.value(context);
        String format = obj0.toString();

        Node node1 = node.jjtGetChild(1);
        Object obj1 = node1.value(context);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date;
        try {
            date = sdf.parse(obj1.toString());
            sdf = new SimpleDateFormat(format);
            String format_date = sdf.format(date);
            writer.write(format_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

}
